<template>
    <div class="role">
        <el-table
                ref="tb"
                  v-loading="loading"
                  :header-cell-style="{ background: '#f6f7fa', height: '60px', color: '#000' }"
                  :data="roleData"
                  style="width: 100%; margin-bottom: 20px"
                  row-key="roleid"
                  border
                  default-expand-all>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="roleid" header-align="center" label="角色id" />
            <el-table-column prop="roleName" align="center" label="角色名称">
                <template #default="{ row }">
                    <el-tag
                            size:="large"
                            class="mx-1"
                            effect="dark"
                            round>
                        {{ row.roleName }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="desc" align="center" label="角色描述">
                <template #default="{ row }">
                    <el-tag
                            size:="large"
                            type="info"
                            class="mx-1"
                            effect="dark"
                            round>
                        {{ row.desc }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" align="center" label="角色状态">
                <template #default="{ row }">
                    <el-switch v-model="row.status"
                               :disabled="!isChild(userStore.userInfo.value.roleid, row.roleid, roleStore.allRoles)"
                               @change="handleSwitchChange(row)"
                               active-value="1"
                               inactive-value="0"
                               size="large"
                               inline-prompt
                               active-text="启用"
                               style="--el-switch-on-color: #1c8bda; --el-switch-off-color: #ff4949"
                               inactive-text="禁用"></el-switch>

                </template>
            </el-table-column>

            <el-table-column prop="address" align="center" label="操作">
                <template #default="{ row }">
                    <el-button v-access="row.roleid" type="primary" @click="handleGrantRole(row)">分配权限</el-button>
                    <el-button v-access="row.roleid">分配角色</el-button>
                </template>
            </el-table-column>
        </el-table>
        <sDrawer

                 v-model:show="drawerShow"
                 :opened-fn="getPermissionRoleList">
            <template #nested>
                <el-tree
                         empty-text="正在加载..."
                         v-loading="treeLoading"
                         ref="treeRef"
                         :data="treeData"
                         show-checkbox
                         node-key="id"
                         default-expand-all
                         highlight-current
                         check-on-click-node
                         check-strictly
                         :props="treeProps" />
            </template>
            <template #customButton>
                <el-button class="twink" type="primary" @click="save">
                    <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-baocun"></use>
                    </svg>

                    <span style="margin:0 10px">保存</span>
                </el-button>
            </template>
        </sDrawer>
    </div>
</template>

<script setup>


import { ref, onMounted, computed } from "vue"
import { ElMessageBox, ElMessage } from "element-plus"
//引入封装的工具方法isChild
import isChild from "@/utils/isChild"
import findChildren from "@/utils/findChild"
//引入权限模块发送请求的方法
import * as permission from "@/api/permission"
import * as roleApi from "@/api/role"
//引入抽屉
import sDrawer from "@/components/sDrawer/index.vue"

// 引入permissionStore

import usePermission from "@/store/permission"

//引入userStore

import useUser from "@/store/users"

//引入角色store

import useRole from "@/store/role"

//使用store
let permissionStore = usePermission()

let userStore = useUser()

let roleStore = useRole();

//加载动画

let loading = ref(true)

//树加载动画
let treeLoading = ref(false)

let roleData = ref([])

//点击的当前角色的id

let currentRoleid = ref(null)

//控制抽屉展开的响应式变量

let drawerShow = ref(false)

let tb = ref()

//获取角色列表

let getRoleList = async () => {
    loading.value = true;
    try {
        let res = await permission.getRoleListApi()
        console.log(res)
        roleData.value = res.data.data;
        loading.value = false
    } catch (e) {
        loading.value = false;
        console.log(e)
    }
}

//创建树形组件引用

let treeRef = ref(null)


//分配权限

let handleGrantRole = (row) => {
    console.log(tb)
    console.log(row)
    drawerShow.value = true
    //保存当前点击的角色id
    currentRoleid.value = row.roleid
}

//组件挂载之后

onMounted(() => {
    //获取角色列表
    getRoleList()
})

//树形控件的数据

const treeProps = {
    children: 'children',
    label: 'desc',
}

const treeData = ref([]);

//请求角色树形数据和所有的权限数据

let getPermissionRoleList = async () => {
    //打开加载动画
    treeLoading.value = true;
    try {
        //并发请求,请求所有的权限数据和角色的权限数据
        let result = await Promise.all([permission.getPermissionListApi(), permission.getCurrentRolePermissionListApi({ type: '1', roleid: currentRoleid.value })])
        // console.log(result)

        //所有的权限数据
        let allPermissions = result[0].data.permissionPaths
        //当前角色的权限数据
        let currentPermissions = result[1].data.data;

        // console.log(allPermissions)
        // console.log(currentPermissions)


        //设置树形的选中

        // console.log(treeRef.value)
        //处理选中id
        let checked_ids = currentPermissions.map(item => item.id)

        treeRef.value.setCheckedKeys(checked_ids)

        console.log(allPermissions)
        //将所有的权限数据扁平化处理

        let flatTree = (data = []) => {
            //扁平化处理后的数据
            let flatArr = []
            //递归函数
            let recursion = (arr = []) => {
                arr.forEach(item => {
                    //声明一个对象,用来存储扁平化处理后的数据
                    let obj = {
                        "_id": item._id,
                        "id": item.id,
                        "path": item.path,
                        "desc": item.desc,
                        "method": item.method,
                        "parentid": item.parentid,
                        "permissions": item.permissions
                    }

                    //如果item有children

                    if (item.children && item.children.length > 0) {
                        //递归调用
                        recursion(item.children)
                    }
                    flatArr.push(obj)
                })
            }
            recursion(data)
            return flatArr;
        }


        //获取了扁平数据
        let flatAllPermissions = flatTree(allPermissions)

        // console.log(flatAllPermissions)

        //从store中获取用户已经拥有的权限id
        let currentPermissionsIds = permissionStore.currentPermissionsIds;
        //和用户已经拥有的权限id进行对比,如果没有对应的数据,那么就需要加上disabled属性
        // console.log(currentPermissionsIds)
        //判断是不是超级管理员

        // console.log(userStore.userInfo.value.roleid)

        if (userStore.userInfo.value.roleid !== '1') {
            flatAllPermissions.forEach(item => {
                if (!currentPermissionsIds.includes(item.id)) {
                    item.disabled = true;
                }
            })
        }

        // console.log(flatAllPermissions)

        //将flatAllPermissions转换成树形结构

        let flatToTree = (data = []) => {

            let tree = []

            data.forEach(item => {

                //先看看自己有没有parentid

                if (!item.parentid) {
                    //没有parentid,说明是根节点
                    tree.push(item)
                } else {

                    //通过parentid找到自己的父亲
                    let parent = data.find(v => v.id === item.parentid)
                    if (parent) {
                        //说明找到了父亲
                        if (!parent.children) {
                            parent.children = []
                        }
                        parent.children.push(item)
                    }
                }

            })

            return tree;
        }


        let treeAllPermissions = flatToTree(flatAllPermissions)

        // console.log(treeAllPermission)

        //给树形组件el-tree赋值


        treeData.value = treeAllPermissions;

        treeLoading.value = false

    } catch (e) {
        console.log(e)
        treeLoading.value = false
    }
}

//保存授权   
let save = () => {
    //获取所有选中权限的id
    console.log(treeRef.value.getCheckedKeys())
    let permission_ids = treeRef.value.getCheckedKeys()
    //弹出确认框,进行交互   
    ElMessageBox.confirm('确认要提交授权吗?', '授权提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
    }).then(async () => {
        //发送请求
        try {
            let res = await permission.grantRoleApi({ roleids: [currentRoleid.value], permission_ids })
            console.log(res)
            if (res.data.code == 200) {
                //关闭抽屉
                drawerShow.value = false
                //提示
                ElMessage.success('授权成功')
            }
        } catch (e) {
            console.log(e)
        }
    }).catch(() => {
        ElMessage.info('已取消授权')
    })
}

//声明自定义指令 控制按钮的禁用状态
let childrens = [];

let vAccess = {
    mounted(el, binding) {
        // console.log(binding)
        //当前角色id
        let currentRoleid = userStore.userInfo.value.roleid
        //目标角色id
        let targetRoleid = binding.value;
        //角色列表
        let roleList = roleStore.allRoles;

        // console.log(targetRoleid)
        // console.log('---current',currentRoleid)
        // console.log(roleList)

        let isChildRole = isChild(currentRoleid, targetRoleid, roleList);

        // console.log(isChildRole)

        //保存当前按钮的类名

        let className = el.className;

        if (!isChildRole) {
            //说明是父级角色
            el.className = className + ' is-disabled'
            //禁用按钮
            el.disabled = true;

        }


        // if (children.find(item => item.roleid == targetRoleid)) {
        //     el.className = className + ' is-disabled'
        //     //禁用按钮
        //     el.disabled = true;
        // }


    }

}


//switch按钮切换的时候

let handleSwitchChange = async (row) => {
    // console.log(val)
    //发起修改请求
    // console.log(row.status,row.roleid)
    try {
        await roleApi.updateRoleApi({ status: row.status, roleid: row.roleid })
        let msg = row.status === '1' ? '角色已启用' : '角色已禁用'
        ElMessage.success(row.roleName + msg)
    } catch (e) {
        console.log(e)
    }
}


</script>

<style scoped>
.icon {
    width: 1.5em;
    height: 1.5em;
}

@keyframes changeImg {
    from {
        left: -90%;
    }

    100% {
        left: 100%;
    }
}

.twink {
    position: relative;
}

.twink::after {
    position: absolute;
    animation: changeImg 3s ease 0s infinite;
    top: 0;
    width: 40%;
    height: 100%;
    content: "";
    background: linear-gradient(to right, rgba(216, 204, 204, 0) 0, rgba(255, 255, 255, 0.905) 50%, rgba(255, 255, 255, 0) 100%);
    transform: skewX(-45deg);
    animation-iteration-count: infinite;
}
</style>

<!-- //用户拥有的权限id
let currentChecksids = [1,2,3,4,5]

//所有的权限对象
let allRolePermission = [
    {
        id:1,,
        parentid:xxxx,
        children:[
         {
            id:"xxx"
         }
        ]
    },
    {
        id:2
    },
    {
        id:10
    }
] -->